﻿/*
Distription: This is Main Class for UI.
Author: Md. Jawed
Emailid: jawed.ace@gmail.com
Dated: 07 Jan 2012
 * */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Proxy;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.Build.Client;
using System.IO;
using TFSBuild;

namespace TFSBuildMonitoringTool
{
    public partial class TFSBuildMonitorTool : Form
    {

        private TfsTeamProjectCollection _tfs;
        private ICommonStructureService _css;
        private IBuildServer _buildServer;
        private IQueuedBuildsView _buildQueue;
        private IBuildController[] _buildController;
        private ProjectInfo[] _projectInfos;
        readonly Build _workingWithBuild = new Build();
#pragma warning disable 612,618
        private DomainProjectPicker _projectPicker = null;
#pragma warning restore 612,618
        private DataSet _resultDataSet = new DataSet();

        private bool _isRanTimeBuild = false;
        private readonly MenuItem[] _menuItems = new MenuItem[4];

        private Thread _threadHistroy = null;
        private Thread _threadRunningBuild = null;
        private readonly Thread _threadGetCurrentBuildStatus = null;

        DateTime _lastStatisticTime;
        private TimeSpan _statisticTime;


        DateTime _lastInProgresTime;
        private TimeSpan _inProgresTime;

        DateTime _lastSatusTime;
        private TimeSpan _statusTime;

        DateTime _lastLatestBuilds;
        private TimeSpan _lastLatestBuildsTime;

        DateTime _lastTimeBumoXmlSettingsWrite;
        private string _bumoXmlSettingsFilePath = string.Empty;

        private bool _isConnectionEstablished = false;

        public TFSBuildMonitorTool()
        {
            InitializeComponent();
            

            this.dataGridViewRes.DataError += new DataGridViewDataErrorEventHandler(dataGridViewRes_DataError);
            this.Hide();
            dateTimePickerFrom.Value = DateTime.Today.AddDays(-1);
            dateTimePickerTo.Value = DateTime.Today;
            InitializeNotifyIcon();
            //string test=Path.Combine("","")
            //  string path1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            _threadGetCurrentBuildStatus = new Thread(() => GetCurrentStatus());
            //Image Location
            //tp://images.zaazu.com/img/laptop-animated-busy-animation-smiley-emoticon-000418-medium.gif
            //http://i69.photobucket.com/albums/i80/jstgermain/ittoolbox/loading.gif
            timerStatistics.Enabled = true;
        }

        /// <summary>
        /// when UI Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void TFSBuildMonitorTool_Load(object sender, EventArgs e)
        {
            try
            {
                string productVersion = Application.ProductVersion;
                this.Text ="BUMO: A TFS BUild MOnitoring Tool,V."+productVersion;
                // string path1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                _bumoXmlSettingsFilePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\BUMOSettings.xml";
                bool flagInitialize = InitializeBUMOFromXMLSettings();
                if (flagInitialize)
                {

                    ConnectTfsAndInitialize(null);


                    //get Build controller Names
                    GetControllersName();
                    //Get Team Project
                    GetProjectList();
                    //Update the Current Status
                    //  GetCurrentStatus();

                    // threadGetCurrentBuildStatus.Start();
                    _isConnectionEstablished = true;
                    _threadGetCurrentBuildStatus.Start();
                }
                else
                {
                    MessageBox.Show("BUMOXMLSettings File not found at the location :" + _bumoXmlSettingsFilePath, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                              MessageBoxIcon.Information);
                    _isConnectionEstablished = false;
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry Connection could not be established!", "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                _isConnectionEstablished = false;
            }


        }

        /// <summary>
        /// TFS Project Server
        /// </summary>
        /// <param name="domainProjectPicker"></param>
        private void ConnectTfsAndInitialize(DomainProjectPicker domainProjectPicker)
        {
            _tfs = domainProjectPicker == null ? TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(BuildMonitorSettings.Tfsurl), new UICredentialsProvider()) : TfsTeamProjectCollectionFactory.GetTeamProjectCollection(domainProjectPicker.SelectedServer != null ? domainProjectPicker.SelectedServer.Uri : new Uri(BuildMonitorSettings.Tfsurl), new UICredentialsProvider());
            _tfs.EnsureAuthenticated();
            _css = _tfs.GetService<ICommonStructureService>();
            _buildServer = _tfs.GetService<IBuildServer>();

            _buildController = _buildServer.QueryBuildControllers();
            textBoxServerUrl.Text = _tfs.Uri.ToString();
            _workingWithBuild.BuildTfsCollection = _tfs;
            _workingWithBuild.BuildBuildServer = _buildServer;
            _workingWithBuild.BuildBuildController = _buildController;
            _workingWithBuild.BuildCommonStructureService = _css;
            _projectInfos = _css.ListAllProjects();


        }
        /// <summary>
        /// Read Settings[XML] file for Monitoring Tool
        /// </summary>
        private bool InitializeBUMOFromXMLSettings()
        {
            // try
            //{

            if (_bumoXmlSettingsFilePath != null)
            {
                //var oFileInfo=FileInfo
                var buildMonitorSettings = new BuildMonitorSettings(_bumoXmlSettingsFilePath);

                _statisticTime = TimeSpan.FromSeconds(BuildStatisticsByBuildReasonSettings.TimeIntervalInSecond);
                _inProgresTime = TimeSpan.FromSeconds(BuildStatisticsInProgressSettings.TimeIntervalInSecond);
                _statusTime = TimeSpan.FromSeconds(StatusOfAgentAndControllerSettings.TimeIntervalInSecond);
                _lastLatestBuildsTime = TimeSpan.FromSeconds(TodaysBuildStatusSettings.TimeIntervalInSecond);

                timerBuildJobsAutoUpdate.Interval = BuildsJobSettings.TimeIntervalInSecond * 1000;
                return true;
            }
            else
            {
                // 
                return false;
            }
            /* }
             catch (Exception exception)
             {
                 MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);

                 return false;
             }*/

        }
        /// <summary>
        /// Initialize the Notify tray icon
        /// </summary>
        private void InitializeNotifyIcon()
        {
            notifyIconTFSBuildMonitorTool.Text = string.Format("BUMO:A TFS Build Monitoring Tool,(c) jawed.ace@gmail.com");
            notifyIconTFSBuildMonitorTool.Visible = true;
            _menuItems[0] = new MenuItem("&Maximized", new EventHandler(this.OnMaximized));
            _menuItems[0].Enabled = true;
            _menuItems[1] = new MenuItem("&Minimized", new EventHandler(this.OnMinimized));
            _menuItems[1].Enabled = true;
            _menuItems[2] = new MenuItem("&Help", new EventHandler(this.OnHelp));
            _menuItems[2].Enabled = true;
            _menuItems[3] = new MenuItem("&Exit", new EventHandler(this.OnExit));
            _menuItems[3].Enabled = true;
            //add the menu items to the context menu of the NotifyIcon
            ContextMenu notifyIconMenu = new ContextMenu(_menuItems);
            notifyIconTFSBuildMonitorTool.ContextMenu = notifyIconMenu;
        }

        /// <summary>
        /// event on when user select maximize
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMaximized(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;

        }
        /// <summary>
        ///  event on when user select Minimized
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMinimized(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;

        }
        /// <summary>
        /// event on when user select Help
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnHelp(object sender, EventArgs e)
        {


        }
        /// <summary>
        /// event on when user select Exit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();

        }
        /// <summary>
        /// get the lists of all Team Projects
        /// </summary>
        private void GetProjectList()
        {
            try
            {
                _css = _tfs.GetService<ICommonStructureService>();
                _projectInfos = _css.ListAllProjects();
                comboBoxFrom.Items.Clear();
                comboBoxTo.Items.Clear();
                foreach (ProjectInfo projectInfo in _projectInfos)
                {
                    comboBoxFrom.Items.Add(projectInfo.Name.ToString());
                    comboBoxTo.Items.Add(projectInfo.Name.ToString());
                }
                if (comboBoxFrom.Items.Count > 0)
                {
                    comboBoxFrom.SelectedIndex = 0;

                }
                if (comboBoxTo.Items.Count > 0)
                {
                    comboBoxTo.SelectedIndex = 0;

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                           MessageBoxIcon.Error);
            }


        }
        /// <summary>
        /// When user clicked on Server button on ui
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnServer_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the TFS project picker object          
                _projectPicker =
                   new DomainProjectPicker(DomainProjectPickerMode.AllowProjectSelect |
                                          DomainProjectPickerMode.AllowMultiSelect);
                if (_projectPicker.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    ConnectTfsAndInitialize(_projectPicker);
                    _isConnectionEstablished = true;
                    GetControllersName();
                    GetProjectList();
                    try
                    {
                        _threadGetCurrentBuildStatus.Start();
                    }
                    catch (ThreadStartException ex)
                    {
                        _threadGetCurrentBuildStatus.Abort();
                        _threadGetCurrentBuildStatus.Start();

                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry Connection could not be established!", "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                _isConnectionEstablished = false;
            }

        }
        /// <summary>
        /// Connect to TFS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void connectToToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Initialize the TFS project picker object          
                _projectPicker =
                       new DomainProjectPicker(DomainProjectPickerMode.AllowProjectSelect |
                                              DomainProjectPickerMode.AllowMultiSelect);
                if (_projectPicker.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    ConnectTfsAndInitialize(_projectPicker);

                }

                GetControllersName();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry Connection could not be established!", "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }

        }


        /// <summary>
        /// Get the Build controller names
        /// </summary>
        private void GetControllersName()
        {

            comboBoxContrlNames.Items.Clear();
            foreach (IBuildController controller in _buildController)
            {
                comboBoxContrlNames.Items.Add(controller.Name);

            }
            if (comboBoxContrlNames.Items.Count > 0)
            {
                comboBoxContrlNames.Items.Insert(0, "ALL");
                comboBoxContrlNames.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// event fiired when Controller names selected from combobox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxContrlNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxAgentsName.Items.Clear();

            if (comboBoxContrlNames.SelectedItem.ToString() != "ALL")
            {
                ReadOnlyCollection<IBuildAgent> agent = AddBuildAgent(comboBoxContrlNames.SelectedItem.ToString());
                foreach (IBuildAgent buildAgent in agent)
                {
                    //if (buildAgent.Enabled)
                    //{
                    comboBoxAgentsName.Items.Add(buildAgent.Name);
                    // }
                }
                if (comboBoxAgentsName != null)
                    if (comboBoxAgentsName.Items.Count > 0)
                    {
                        comboBoxAgentsName.Items.Insert(0, "ALL");
                        comboBoxAgentsName.SelectedIndex = 0;
                    }
                    else
                    {
                        comboBoxAgentsName.SelectedItem = "No Agent Associated with this controller.";
                    }
            }
            else
            {
                comboBoxAgentsName.Items.Insert(0, "ALL");
                comboBoxAgentsName.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// call Add Builds Agent 
        /// </summary>
        /// <param name="strControllerNameSelected"></param>
        /// <returns></returns>
        private ReadOnlyCollection<IBuildAgent> AddBuildAgent(string strControllerNameSelected)
        {
            ReadOnlyCollection<IBuildAgent> buildAgents = null;
            foreach (IBuildController controller in
                _buildController.Where(controller => controller.Name == strControllerNameSelected))
                buildAgents = controller.Agents;
            return buildAgents;
        }

        /// <summary>
        /// Event to Execute the corresponding settings selected at UI.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void buttonGetResult_Click(object sender, EventArgs e)
        {
            if (_isConnectionEstablished)
            {
                switch (comboBoxContrlNames.SelectedIndex)
                {
                    case -1:
                        MessageBox.Show("Please Select Controller from Controllers Drop Down list.",
                                        "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        break;
                    default:
                        try
                        {
                            ExcuteTheBuildOperation();
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }
                        break;
                }
            }
            else
            {
                MessageBox.Show("Not Connected to TFS Server.", "BUMO: A TFS Build Monitoring Tool!!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// Call the method based on Check box selected on UI
        /// </summary>
        private void ExcuteTheBuildOperation()
        {
            try
            {
                if (buttonGetResult.Enabled)
                {
                    if (radioButtonBldHist.Checked || radioButtonBldRng.Checked || radioButtonBldRanFor.Checked)
                    {
                        buttonGetResult.Enabled = false;
                        groupBoxOperation.Enabled = false;
                        pictureBoxWorkingBusy.Visible = true;

                        if (radioButtonBldHist.Checked)
                        {
                            _isRanTimeBuild = false;
                            GetBuildHistory();
                        }
                        else if (radioButtonBldRng.Checked)
                        {
                            _isRanTimeBuild = false;
                            GetRunningBuild();

                        }
                        else if (radioButtonBldRanFor.Checked)
                        {
                            _isRanTimeBuild = true;
                            GetBuildRanForTimePeriod();

                        }
                        else
                        {
                            MessageBox.Show("Please select an option!", "BUMO: A TFS Build Monitoring Tool!!",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception exception)
            {

                MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                buttonGetResult.Enabled = true;
                groupBoxOperation.Enabled = true;
                pictureBoxWorkingBusy.Visible = false;
            }
        }

        /// <summary>
        /// Get the History of the builds
        /// </summary>
        private void GetBuildHistory()
        {
            try
            {

                string agentName = string.Empty;
                string controllerName = string.Empty;
                if (comboBoxAgentsName.SelectedItem.ToString() != "ALL")
                {
                    agentName = comboBoxAgentsName.SelectedItem.ToString();
                }
                if (comboBoxContrlNames.SelectedItem.ToString() != "ALL")
                {
                    controllerName = comboBoxContrlNames.SelectedItem.ToString();

                }

                // var dataSetBuildHistory = _workingWithBuild.BuildsOnAgent(dateTimePickerFrom.Value, agentName);
                _threadHistroy = new Thread(() => GetBuildsDetails(dateTimePickerFrom.Value, agentName, controllerName));
                _threadHistroy.Start();



            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);

                //MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                //                MessageBoxButtons.OK,
                //                MessageBoxIcon.Error);
            }

        }


        /// <summary>
        /// Get the Build History Details
        /// </summary>
        /// <param name="dateTime"></param>
        /// <param name="agent"></param>
        /// <param name="controllerName"></param>
        private void GetBuildsDetails(DateTime dateTime, string agent, string controllerName)
        {
            try
            {
                _resultDataSet.Clear();
                _resultDataSet = _workingWithBuild.BuildsOnAgent(dateTime, agent, controllerName);

                Action<DataTable> action = new Action<DataTable>(DisplayResult);// DisplayResult(dtview.Table);
                this.BeginInvoke(action, _resultDataSet.Tables[0]);// action(_resultDataSet.Tables[0]);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
                //MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                //                MessageBoxButtons.OK,
                //                MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// this will provide the Running build on the UI for the user.
        /// </summary>
        private void GetRunningBuild()
        {
            try
            {

                _threadRunningBuild = new Thread(() => GetRunningBuildsDetails());
                _threadRunningBuild.Start();

                //buttonGetResult.Enabled = false;
                //groupBoxOperation.Enabled = false;
                //pictureBoxWorkingBusy.Visible = true;

            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
                //MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                //               MessageBoxIcon.Information);
                //buttonGetResult.Enabled = true;
                //groupBoxOperation.Enabled = true;
                //pictureBoxWorkingBusy.Visible = false;

            }

        }

        /// <summary>
        /// get the Running Build call
        /// </summary>
        private void GetRunningBuildsDetails()
        {
            _resultDataSet.Clear();
            _resultDataSet = _workingWithBuild.BuildsOnAgent(DateTime.Now.AddHours(-5), string.Empty, string.Empty); //_workingWithBuild.RunningBuilds();
            DataView dtview = GetInProgressBuild(_resultDataSet);

            // _resultDataSet = dtview.Table.DataSet;

            DataTable dtable = new DataTable();
            dtable = dtview.Table.Clone();
            foreach (DataRowView drowview in dtview)
                dtable.ImportRow(drowview.Row);
            //Action action = DisplayResult;
            //this.BeginInvoke(action);
            Action<DataTable> action = new Action<DataTable>(DisplayResult);// DisplayResult(dtview.Table);
            this.BeginInvoke(action, dtable);// action(dtview.Table);

        }

        /// <summary>
        /// Use this to formate the datagrid on ui
        /// </summary>
        private void FormateTheDataGrid(DataGridView dataGridView)
        {
            try
            {
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    foreach (DataGridViewColumn column in dataGridView.Columns)
                    {
                        if (column.Index == 5)
                        {
                            if (row.Cells[column.Name].Value != null)
                                switch (row.Cells[column.Name].Value.ToString())
                                {
                                    case "Failed":
                                        row.Cells[5].Style.ForeColor = Color.Red;
                                        row.Cells[6].Style.ForeColor = Color.Red;
                                        break;
                                    case "InProgress":
                                        row.Cells[5].Style.ForeColor = System.Drawing.Color.Magenta;
                                        row.Cells[6].Style.ForeColor = System.Drawing.Color.Magenta;
                                        break;
                                    case "PartiallySucceeded":
                                        row.Cells[5].Style.ForeColor = System.Drawing.Color.DarkOrange;
                                        row.Cells[6].Style.ForeColor = System.Drawing.Color.DarkOrange;
                                        break;
                                    case "Succeeded":
                                        row.Cells[5].Style.ForeColor = System.Drawing.Color.Green;
                                        row.Cells[6].Style.ForeColor = System.Drawing.Color.Green;
                                        break;
                                    default:
                                        row.Cells[5].Style.ForeColor = System.Drawing.Color.Blue;
                                        row.Cells[6].Style.ForeColor = System.Drawing.Color.Blue;
                                        break;
                                }
                        }
                    }
                }

            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                               MessageBoxIcon.Information);
            }
            finally
            {
                dataGridView.Refresh();
            }

        }

        /// <summary>
        /// Method to Format the Data Grid shown on UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewRes_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            FormateTheDataGrid(dataGridViewRes);
        }

        /// <summary>
        /// This method is responsible to display result in DataGrid
        /// </summary>
        private void DisplayResult(DataTable contacts)
        {
            if (_resultDataSet != null)
            {
                //  DataTable contacts = _resultDataSet.Tables[0];
                if (_isRanTimeBuild)
                {
                    EnumerableRowCollection<DataRow> queryData = from contact in contacts.AsEnumerable()
                                                                 where
                                                                     contact.Field<double>("Ran-Minutes") >
                                                                     double.Parse(textBoxRanTime.Text)
                                                                 orderby contact.Field<double>("Ran-Minutes")
                                                                 select contact;

                    DataView viewData = queryData.AsDataView();
                    dataGridViewRes.DataSource = viewData;

                }
                else
                {
                    // dataGridViewRes.DataMember = _resultDataSet.Tables[0].ToString();
                    dataGridViewRes.DataSource = contacts;

                }
            }
            buttonGetResult.Enabled = true;
            groupBoxOperation.Enabled = true;
            pictureBoxWorkingBusy.Visible = false;
        }

        /// <summary>
        /// Method to get Build whihc ran for period of time
        /// </summary>
        private void GetBuildRanForTimePeriod()
        {
            try
            {

                if (!string.IsNullOrEmpty(textBoxRanTime.Text))
                {
                    if (!string.IsNullOrWhiteSpace(textBoxRanTime.Text))
                    {
                        GetBuildHistory();
                    }

                }
                else
                {
                    MessageBox.Show("Please Proviod Ran Time To get the Builds!", "BUMO: A TFS Build Monitoring Tool!!",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }
            catch (Exception exception)
            {

                MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// refresh Button Event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            if (!_isConnectionEstablished)
            {
                MessageBox.Show("Not Connected to TFS Server.", "BUMO: A TFS Build Monitoring Tool!!",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
            else
            {
                if (comboBoxContrlNames.SelectedIndex == -1)
                {
                    MessageBox.Show("Please Select Controller from Controllers Drop Down list.",
                                    "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                else
                {
                    try
                    {
                        if (!buttonGetResult.Enabled)
                        {
                            MessageBox.Show("Busy, Try after some time!", "BUMO: A TFS Build Monitoring Tool!!",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                        else
                        {
                            ExcuteTheBuildOperation();
                        }
                    }
                    catch (Exception exception)
                    {
                        //MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!", MessageBoxButtons.OK,
                        //                MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// Update the Result on Corresponding Static
        /// </summary>
        /// <param name="dataSet"></param>
        private void UpdateStatistics(DataSet dataSetUpdateStatistics)
        {

            DataTable contacts = dataSetUpdateStatistics.Tables[0];
            // string controllerNameToUpdate = string.Empty;
            foreach (string controllerNameToUpdate in BuildMonitorSettings.TfsMonitorToolControllersToUpdate)
            {

                //get the Corresponding controller Values
                List<string> listControllerValues = GetControllerResultValue(controllerNameToUpdate);
                if (listControllerValues.Count == 0) continue;
                DataTable dataTableStatic = new DataTable();

                dataTableStatic = GetDataTableColumnsForStatics(dataTableStatic, controllerNameToUpdate);

                //for each controller

                for (int i = 1; i < listControllerValues.Count; i++)
                {
                    DataRow row = dataTableStatic.NewRow();
                    string mainValue = listControllerValues[i].ToString();

                    row[0] = mainValue;
                    int col = 1;
                    int total = 0;
                    foreach (var buildStatus in BuildMonitorSettings.BuildsStatus)
                    {

                        EnumerableRowCollection<DataRow> queryData = from contact in contacts.AsEnumerable()
                                                                     where
                                                                         contact.Field<string>("Status") ==
                                                                         buildStatus
                                                                         &&
                                                                         contact.Field<string>(
                                                                             controllerNameToUpdate) ==
                                                                         mainValue
                                                                     select contact;

                        DataView viewData = queryData.AsDataView();
                        var count = viewData.Count.ToString();
                        row[col] = count;
                        total += int.Parse(count);
                        col++;
                    }
                    row[col] = total;
                    dataTableStatic.Rows.Add(row);
                }
                UpdateCorrespondingDataGrid(controllerNameToUpdate, dataTableStatic);

            }

        }

        /// <summary>
        /// Get the Result Corresponding to the controller name provided
        /// </summary>
        /// <param name="controllerNameToUpdate"></param>
        /// <returns></returns>
        private List<string> GetControllerResultValue(string controllerNameToUpdate)
        {
            List<string> result = new List<string>();
            //"Build Controller", "Agent", "Build Reason" 
            switch (controllerNameToUpdate)
            {
                case "Build Controller":
                    result = _workingWithBuild.GetBuildControllersName();
                    break;
                case "Agent":
                    result = _workingWithBuild.GetBuildAgentsName();
                    break;
                case "Build Reason":
                    result = BuildMonitorSettings.BuildsReason;
                    break;
                case "Summary":

                    break;

            }

            return result;

        }

        /// <summary>
        /// Update the Corresponding dataGrid on UI
        /// </summary>
        /// <param name="datagridtoUpdate"></param>
        /// <param name="resultToShowInDataGrid"></param>
        /// <returns></returns>
        private void UpdateCorrespondingDataGrid(string datagridtoUpdate, DataTable resultToShowInDataGrid)
        {
            var updategrid = new DataGridView();
            //"Build Controller", "Agent", "Build Reason" 
            switch (datagridtoUpdate)
            {
                case "Build Controller":
                    updategrid = dataGridViewCon;
                    break;
                case "Agent":
                    updategrid = dataGridViewAgent;
                    break;
                case "Build Reason":
                    if (dataGridViewBuildReason.Enabled)
                    {
                        updategrid = dataGridViewBuildReason;

                    }
                    else
                    {
                        return;
                    }
                    break;

            }
            updategrid.DataSource = resultToShowInDataGrid;

        }

        /// <summary>
        /// set the data column for the build history to displayed
        /// </summary>
        /// <param name="dtBuildDetails"></param>
        /// <param name="strFirstColumnName"></param>
        /// <returns></returns>
        private static DataTable GetDataTableColumnsForStatics(DataTable dtBuildDetails, string strFirstColumnName)
        {
            dtBuildDetails.Columns.Add(strFirstColumnName, typeof(string));
            foreach (string item in BuildMonitorSettings.BuildsStatus)
            {
                dtBuildDetails.Columns.Add(item, typeof(string));
            }

            dtBuildDetails.Columns.Add("Total", typeof(string));
            return dtBuildDetails;
        }

        /// <summary>
        /// set the data column to show the status of  controlerr and Agent
        /// </summary>
        /// <param name="dtBuildDetails"></param>
        /// <returns></returns>
        private static DataTable GetDataTableColumnsForStatus(DataTable dtBuildDetails)
        {
            dtBuildDetails.Columns.Add("Name", typeof(string));
            dtBuildDetails.Columns.Add("Enabled", typeof(string));
            //dtBuildDetails.Columns.Add("Online", typeof(bool));
            return dtBuildDetails;
        }

        /// <summary>
        /// set the data column to show the status of  controlerr and Agent
        /// </summary>
        /// <param name="dtBuildDetails"></param>
        /// <returns></returns>
        private static DataTable GetDataTableColumnsForBuildsJobSummary(DataTable dtBuildDetails)
        {
            dtBuildDetails.Columns.Add("Status", typeof(string));
            dtBuildDetails.Columns.Add("Count", typeof(string));
            //dtBuildDetails.Columns.Add("Online", typeof(bool));
            return dtBuildDetails;
        }
        /// <summary>
        /// Current Status of Build
        /// </summary>
        public void GetCurrentStatus()
        {
            if (_isConnectionEstablished)
            {
                _buildQueue = _buildServer.CreateQueuedBuildsView();
                _buildQueue.StatusFilter = QueueStatus.Completed | QueueStatus.InProgress;
                // Hook up our build queue listener.
                _buildQueue.StatusChanged += new StatusChangedEventHandler(buildQueue_StatusChanged);
                _buildQueue.Connect(1000, groupBoxCurrent);
            }

        }

        /// <summary>
        /// Event fired when the lastest one build status changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void buildQueue_StatusChanged(object sender, StatusChangedEventArgs e)
        {
            //if (IsConnectionEstablished)
            //{

            if (e.Changed && _buildQueue.QueuedBuilds.Length > 0)
            {

                int lastItem = _buildQueue.QueuedBuilds.Length - 1;

                IQueuedBuild queuedBuild = _buildQueue.QueuedBuilds[lastItem];
                if (queuedBuild.Build != null)
                {
                    IBuildDetail detail = queuedBuild.Build;
                    labelStatusRe.Text = detail.Status.ToString();
                    labelProjRes.Text = detail.TeamProject.ToString();
                    labelBuildNumRes.Text = detail.BuildNumber.ToString();
                    labelDefRes.Text = detail.BuildDefinition.Name;
                    labeltriggerRes.Text = detail.RequestedFor.ToString();

                    switch (detail.Status)
                    {
                        case BuildStatus.Failed:
                            statusPictureBox.Image = global::TFSBuildMonitoringTool.Properties.Resources.jawed1_bad;
                            break;
                        case BuildStatus.InProgress:
                        case BuildStatus.NotStarted:
                            statusPictureBox.Image = global::TFSBuildMonitoringTool.Properties.Resources.jawed_queue;
                            break;
                        case BuildStatus.PartiallySucceeded:
                            statusPictureBox.Image = global::TFSBuildMonitoringTool.Properties.Resources.jawed_partial;
                            break;
                        case BuildStatus.Stopped:
                            statusPictureBox.Image = global::TFSBuildMonitoringTool.Properties.Resources.jawed_stop;
                            break;
                        case BuildStatus.Succeeded:
                            statusPictureBox.Image = global::TFSBuildMonitoringTool.Properties.Resources.jawed_good;
                            break;
                        default:
                            break;
                    }

                }
            }
            // }
        }

        /// <summary>
        /// Timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerStatistics_Tick(object sender, EventArgs e)
        {
            try
            {
                if (_isConnectionEstablished)
                {
                    UsingbackGroudWorker();
                    IsXmlChangeByUser();
                }
            }
            catch (Exception exception)
            {
                //MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                //           MessageBoxButtons.OK,
                //           MessageBoxIcon.Error);
                _isConnectionEstablished = false;
            }


        }
        /// <summary>
        /// Look for settings file
        /// </summary>
        private void IsXmlChangeByUser()
        {
            try
            {
                if (File.Exists(_bumoXmlSettingsFilePath))
                {
                    FileInfo oFileInfo = new FileInfo(_bumoXmlSettingsFilePath);
                    DateTime xmlWriteDateTime = oFileInfo.LastWriteTime;
                    if (_lastTimeBumoXmlSettingsWrite != xmlWriteDateTime)
                    {
                        _lastTimeBumoXmlSettingsWrite = xmlWriteDateTime;
                        InitializeBUMOFromXMLSettings();

                    }

                }

            }
            catch (Exception ex)
            {
                //To do

            }


        }
        /// <summary>
        /// Use of Background Worker
        /// </summary>
        public void UsingbackGroudWorker()
        {
            if (_isConnectionEstablished)
            {
                if (BuildStatisticsInProgressSettings.AutoUpdate)
                {

                    if (DateTime.Now - _lastInProgresTime >= _inProgresTime)
                    {
                        _lastInProgresTime = DateTime.Now;
                        if (!BackgroundWorkerInProgress.IsBusy)
                        {
                            this.BackgroundWorkerInProgress.RunWorkerAsync();
                        }
                    }
                }

                if (BuildStatisticsByBuildReasonSettings.AutoUpdate)
                {

                    if (DateTime.Now - _lastStatisticTime >= _statisticTime)
                    {
                        _lastStatisticTime = DateTime.Now;
                        if (!BackgroundWorkerStatistic.IsBusy)
                        {
                            this.BackgroundWorkerStatistic.RunWorkerAsync();
                        }
                    }
                }
                if (StatusOfAgentAndControllerSettings.AutoUpdate)
                {
                    if (DateTime.Now - _lastSatusTime >= _statusTime)
                    {
                        _lastSatusTime = DateTime.Now;
                        if (!backgroundWorkerStatus.IsBusy)
                        {
                            this.backgroundWorkerStatus.RunWorkerAsync();
                        }
                    }
                }

                if (radioButtonTopBuilds.Checked)
                {
                    if (TodaysBuildStatusSettings.AutoUpdate)
                    {
                        if (DateTime.Now - _lastLatestBuilds >= _lastLatestBuildsTime)
                        {
                            _lastLatestBuilds = DateTime.Now;
                            if (!backgroundWorkerLatestBuild.IsBusy)
                            {
                                this.backgroundWorkerLatestBuild.RunWorkerAsync();
                            }
                        }

                    }
                }

                // this.BackgroundWorkerStatus.RunWorkerAsync();
            }

        }

        /// <summary>
        /// Get In Progress Build and show this on UI
        /// </summary>
        public DataView GetInProgressBuild(DataSet datasetInProgressBuilds)
        {

            DataTable contacts = datasetInProgressBuilds.Tables[0];
            EnumerableRowCollection<DataRow> queryData = from contact in contacts.AsEnumerable()
                                                         where contact.Field<string>("Status") == "InProgress"
                                                         orderby contact.Field<DateTime>("Run Date")
                                                         select contact;

            DataView viewData = queryData.AsDataView();

            // dataGridViewProgress.DataSource = viewData;
            return viewData;


        }

        /// <summary>
        /// Update the status of Controllers and Agents on UI.
        /// </summary>
        private void GetStatusofControllerAndAgents(List<BuildControllerAndAgentNamesStatus> result)
        {
            DataTable dataTableStatic = new DataTable();
            dataTableStatic = GetDataTableColumnsForStatus(dataTableStatic);

            foreach (BuildControllerAndAgentNamesStatus buildControllerAndAgentNamesStatuse in result)
            {
                DataRow row = dataTableStatic.NewRow();

                row[0] = buildControllerAndAgentNamesStatuse.Name;
                row[1] = buildControllerAndAgentNamesStatuse.Status.ToString();
                dataTableStatic.Rows.Add(row);
            }
            result.Clear();

            result = _workingWithBuild.GetBuildAgentsNameWithStatus();
            foreach (BuildControllerAndAgentNamesStatus buildControllerAndAgentNamesStatuse in result)
            {
                DataRow row = dataTableStatic.NewRow();

                row[0] = buildControllerAndAgentNamesStatuse.Name;
                row[1] = buildControllerAndAgentNamesStatuse.Status.ToString();
                dataTableStatic.Rows.Add(row);
            }

            dataGridViewStatusConAgent.DataSource = dataTableStatic;

        }

        /// <summary>
        /// Update In Progress Builds Report on UI.
        /// </summary>
        private void BackgroundWorkerInProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            DataSet argument = e.Argument as DataSet;
            argument = _workingWithBuild.BuildsOnAgent(DateTime.Now.AddHours(-5), string.Empty, string.Empty);
            e.Result = argument;

        }

        private void BackgroundWorkerInProgress_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
        {

            DataSet dataSet = e.Result as DataSet;
            if (dataSet != null)
            {
                DataView dtview = GetInProgressBuild(dataSet);
                dataGridViewProgress.DataSource = dtview;
            }

        }

        /// <summary>
        /// Update Statistic Report on UI.
        /// </summary>
        private void BackgroundWorkerStatistic_DoWork(object sender, DoWorkEventArgs e)
        {
            DataSet argument = e.Argument as DataSet;
            argument = _workingWithBuild.BuildsOnAgent(dateTimePickerFrom.Value, string.Empty, string.Empty);
            e.Result = argument;
        }

        private void BackgroundWorkerStatistic_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataSet dataSet = e.Result as DataSet;
            if (dataSet != null)
            {
                UpdateStatistics(dataSet);
                UpdateBuildsJobSummaryView(dataSet);
            }
        }

        /// <summary>
        /// Update the Builds Job SUmmary Statistic on UI
        /// </summary>
        /// <param name="dataSet"></param>
        private void UpdateBuildsJobSummaryView(DataSet dataSet)
        {
            int totalCount = dataSet.Tables[0].Rows.Count;

            DataTable contacts = dataSet.Tables[0];
            // string controllerNameToUpdate = string.Empty;
            DataRow row;
            DataTable dataTableStatic = new DataTable();

            dataTableStatic = GetDataTableColumnsForBuildsJobSummary(dataTableStatic);

            DataView viewData = new DataView();
            // int col = 1;
            foreach (var buildStatus in BuildMonitorSettings.BuildsStatus)
            {
                row = dataTableStatic.NewRow();

                EnumerableRowCollection<DataRow> queryData = from contact in contacts.AsEnumerable()
                                                             where
                                                                 contact.Field<string>("Status") ==
                                                                 buildStatus
                                                             select contact;

                viewData = queryData.AsDataView();
                var count = viewData.Count.ToString();
                row[0] = buildStatus;
                row[1] = count;
                dataTableStatic.Rows.Add(row);

            }
            row = dataTableStatic.NewRow();
            row[0] = "Total";
            row[1] = totalCount;
            dataTableStatic.Rows.Add(row);

            dataGridViewSummaryBuilds.DataSource = dataTableStatic;

        }

        private void backgroundWorkerStatus_DoWork(object sender, DoWorkEventArgs e)
        {

            List<BuildControllerAndAgentNamesStatus> result = e.Argument as List<BuildControllerAndAgentNamesStatus>;

            result = _workingWithBuild.GetBuildControllersNameWithStatus();
            e.Result = result;

        }

        private void backgroundWorkerStatus_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<BuildControllerAndAgentNamesStatus> result = e.Result as List<BuildControllerAndAgentNamesStatus>;

            GetStatusofControllerAndAgents(result);
        }

        /// <summary>
        /// Update the Todays Builds Details on UI
        /// </summary>
        /// <param name="dataSet"></param>
        private void backgroundWorkerLatestBuild_DoWork(object sender, DoWorkEventArgs e)
        {
            DataSet argument = e.Argument as DataSet;
            argument = _workingWithBuild.BuildsOnAgent(DateTime.Today, string.Empty, string.Empty);
            e.Result = argument;
        }

        private void backgroundWorkerLatestBuild_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataSet dataSet = e.Result as DataSet;
            if (dataSet != null)
            {
                dataGridViewLatestBuild.DataMember = dataSet.Tables[0].ToString();
                dataGridViewLatestBuild.DataSource = dataSet;
            }
        }

        /// <summary>
        /// This event would move the build
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBuildClone_Click(object sender, EventArgs e)
        {
            try
            {
                labelStatusBuild.Text = string.Empty;
                string fromBuild = textBoxBuildName.Text;
                string toBuild = textBoxBuildNew.Text;
                if (!string.IsNullOrEmpty(textBoxBuildName.Text))
                {
                    if (string.IsNullOrEmpty(toBuild))
                    {
                        toBuild = fromBuild;
                    }
                    _workingWithBuild.CloneBuild(comboBoxFrom.SelectedItem.ToString(), comboBoxTo.SelectedItem.ToString(), fromBuild, toBuild);
                    labelStatusBuild.Text = "Build Has been Cloned and The Cloned-Build would be Disable.";
                    labelStatusBuild.ForeColor = Color.Green;
                }
                else
                {
                    throw new Exception("Provide Build Name.");

                }


            }
            catch (Exception exception)
            {
                labelStatusBuild.Text = "ERROR: " + exception.Message;
                labelStatusBuild.ForeColor = Color.Red;

            }

        }

        /// <summary>
        /// AutoUpdate Checkbox checked by the user on Builds Tab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxAutUpdate_CheckedChanged(object sender, EventArgs e)
        {
            if (_isConnectionEstablished)
            {
                if (checkBoxAutUpdate.Checked)
                {
                    //if (buttonGetResult.Enabled)
                    //{
                    //    ExcuteTheBuildOperation();

                    //}
                    timerBuildJobsAutoUpdate.Enabled = true;
                    timerBuildJobsAutoUpdate.Interval = BuildsJobSettings.TimeIntervalInSecond * 1000;
                }
                else
                {
                    timerBuildJobsAutoUpdate.Enabled = false;
                }
            }

        }
        /// <summary>
        /// Timer ot Start on Build Tab for Auto Update
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerBuildJobsAutoUpdate_Tick(object sender, EventArgs e)
        {
            if (buttonGetResult.Enabled)
            {
                ExcuteTheBuildOperation();
            }

        }
        /// <summary>
        /// Check box of Top Build Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButtonTopBuilds_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonTopBuilds.Checked)
            {
                groupBoxBuildReason.Text = "Todays builds Status";
                dataGridViewBuildReason.Enabled = false;
                dataGridViewBuildReason.Visible = false;
                dataGridViewLatestBuild.Visible = true;
                dataGridViewLatestBuild.Enabled = true;
            }
            else
            {
                groupBoxBuildReason.Text = "Statistics of Builds job by Build Reason";
                dataGridViewBuildReason.Enabled = true;
                dataGridViewBuildReason.Visible = true;
                dataGridViewLatestBuild.Visible = false;
                dataGridViewLatestBuild.Enabled = false;
            }

        }

        /// <summary>
        /// Update the Todays Build Rows with color coding
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewLatestBuild_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            FormateTheDataGrid(dataGridViewLatestBuild);
        }

        /// <summary>
        /// Use this to formate the datagrid of status on ui
        /// </summary>
        private void FormateTheDataGridForStatus(DataGridView dataGridView)
        {
            try
            {
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    foreach (DataGridViewColumn column in dataGridView.Columns)
                    {
                        if (column.Index == 1)
                        {

                            if (row.Cells[column.Name].Value != null)
                                switch (row.Cells[column.Name].Value.ToString().ToUpper())
                                {
                                    case "TRUE":
                                        row.Cells[1].Style.ForeColor = Color.Green;
                                        break;
                                    case "FALSE":
                                        row.Cells[1].Style.ForeColor = System.Drawing.Color.Red;
                                        break;

                                    default:
                                        row.Cells[1].Style.ForeColor = System.Drawing.Color.Magenta;
                                        break;
                                }
                        }
                    }
                }

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            }
            finally
            {
                dataGridView.Refresh();
            }

        }
        /// <summary>
        /// DataGridView of Status 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewStatusConAgent_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            FormateTheDataGridForStatus(dataGridViewStatusConAgent);
        }

        /// <summary>
        /// Refresh the Project list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBuildCloneRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                GetProjectList();
            }
            catch (Exception exception)
            {

                MessageBox.Show(exception.Message, "BUMO: A TFS Build Monitoring Tool!!",
                          MessageBoxButtons.OK,
                          MessageBoxIcon.Error);
            }

        }


        /// <summary>
        /// To handle the Deafult error from data Grid view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="anError"></param>
        public void dataGridViewRes_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {
            // MessageBox.Show("Error happened " + anError.Context.ToString());

            if (anError.Context == DataGridViewDataErrorContexts.Commit)
            {
                MessageBox.Show("Commit error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
            {
                MessageBox.Show("Cell change");
            }
            if (anError.Context == DataGridViewDataErrorContexts.Parsing)
            {
                MessageBox.Show("parsing error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
            {
                MessageBox.Show("leave control error");
            }

            if ((anError.Exception) is ConstraintException)
            {
                DataGridView view = (DataGridView)sender;
                view.Rows[anError.RowIndex].ErrorText = "an error";
                view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";

                anError.ThrowException = false;
            }

        }
    }

}
